package com.apes.framework.plugin.soe.metadata;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 功能：场景
 *
 * @author xul
 * @create 2018-09-21 11:37
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Scene.CONST_TABLE_NAME)
public class Scene extends BaseModel {
    public static final String CONST_TABLE_NAME = "soe_scene";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "场景")
    @Comment("编码")
    private String id;   //场景编码

    @Column(name = "name", nullable = false, length = 60)
    @Comment("场景名称")
    private String name;

    @Column(name = "valid", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("是否有效")
    private boolean valid = true;

    @Column(name = "rightful", nullable = false, columnDefinition = "number(1,0) default 0")
    @Comment("合法标记")
    private boolean rightful = false;

    @OneToMany(mappedBy = "scene", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<SceneRole> sceneRoles = new HashSet(); //场景角色

    public Set<SceneRole> getSceneRoles() {
        for (SceneRole flow : sceneRoles) {
            flow.setScene(this);
        }
        return sceneRoles;
    }

    @JSONField(serialize = false)
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "scene")
    @OrderBy("step asc")
    private List<SceneFlow> sceneFlows; //场景流

    public boolean check() {
        if (this.getSceneFlows().stream().filter(sceneFlow -> sceneFlow.isStarted()).count() != 1) return false;
        if (this.getSceneFlows().stream().filter(sceneFlow -> sceneFlow.isFinish()).count() != 1) return false;
        return true;
    }
}
